package com.galen.wxRead.utils;

import java.util.*;

public class XmlUtil {

    /**
     * 字符串处理工具类
     *
     * @author suguolong
     */
    public static class ToolString {
        /**
         public static void main(String[] args) {
         String xmlText =
         "<TimelineObject>\n" +
         "    <id>\n" +
         "        <![CDATA[13127761385824923735]]>\n" +
         "    </id>\n" +
         "    <username>\n" +
         "        <![CDATA[wxid_ed01ehm3m2uq22]]>\n" +
         "    </username>\n" +
         "    <createTime>\n" +
         "        <![CDATA[1564951108]]>\n" +
         "    </createTime>\n" +
         "    <contentDescShowType>0</contentDescShowType>\n" +
         "    <contentDescScene>0</contentDescScene>\n" +
         "    <private>\n" +
         "        <![CDATA[0]]>\n" +
         "    </private>\n" +
         "    <contentDesc>\n" +
         "        <![CDATA[看电视剧看得我热泪盈眶，总有一种莫名的感觉，又亲切又悲伤的，观看过程一直哭啊……[大哭][大哭]]]>\n" +
         "    </contentDesc>\n" +
         "    <contentattr>\n" +
         "        <![CDATA[0]]>\n" +
         "    </contentattr>\n" +
         "    <sourceUserName></sourceUserName>\n" +
         "    <sourceNickName></sourceNickName>\n" +
         "    <statisticsData></statisticsData>\n" +
         "    <weappInfo>\n" +
         "        <appUserName></appUserName>\n" +
         "        <pagePath></pagePath>\n" +
         "    </weappInfo>\n" +
         "    <canvasInfoXml></canvasInfoXml>\n" +
         "    <ContentObject>\n" +
         "        <contentStyle>\n" +
         "            <![CDATA[1]]>\n" +
         "        </contentStyle>\n" +
         "        <contentSubStyle>\n" +
         "            <![CDATA[0]]>\n" +
         "        </contentSubStyle>\n" +
         "        <title></title>\n" +
         "        <description></description>\n" +
         "        <contentUrl></contentUrl>\n" +
         "        <mediaList>\n" +
         "            <media>\n" +
         "                <id>\n" +
         "                    <![CDATA[13127761386476941374]]>\n" +
         "                </id>\n" +
         "                <type>\n" +
         "                    <![CDATA[2]]>\n" +
         "                </type>\n" +
         "                <title></title>\n" +
         "                <description></description>\n" +
         "                <private>\n" +
         "                    <![CDATA[0]]>\n" +
         "                </private>\n" +
         "                <url type=\\\"1\\\">\n" +
         "                    <![CDATA[http://szmmsns.qpic.cn/mmsns/oSSMibuEp2Xeh8EfTAYYYZXRoR9dU8VM97p6fFayPV06Aiccgq9HSicuF9JA5EP8OTCoiaeH69slwGE/0]]>\n" +
         "                </url>\n" +
         "                <thumbMoment type=\\\"1\\\">\n" +
         "                    <![CDATA[http://szmmsns.qpic.cn/mmsns/oSSMibuEp2Xeh8EfTAYYYZXRoR9dU8VM97p6fFayPV06Aiccgq9HSicuF9JA5EP8OTCoiaeH69slwGE/150]]>\n" +
         "                </thumbMoment>\n" +
         "                <size totalSize=\\\"94102.0\\\" width=\\\"2280.0\\\" height=\\\"1080.0\\\"></size>\n" +
         "            </media>\n" +
         "            <media>\n" +
         "                <id>\n" +
         "                    <![CDATA[13127761386525831264]]>\n" +
         "                </id>\n" +
         "                <type>\n" +
         "                    <![CDATA[2]]>\n" +
         "                </type>\n" +
         "                <title></title>\n" +
         "                <description></description>\n" +
         "                <private>\n" +
         "                    <![CDATA[0]]>\n" +
         "                </private>\n" +
         "                <url type=\\\"1\\\">\n" +
         "                    <![CDATA[http://szmmsns.qpic.cn/mmsns/oSSMibuEp2Xeh8EfTAYYYZXRoR9dU8VM9DqcdCYrIP0ibCgibSCfn2aVDOGuAolwrcDUS0ZPqMvcTU/0]]>\n" +
         "                </url>\n" +
         "                <thumbMoment type=\\\"1\\\">\n" +
         "                    <![CDATA[http://szmmsns.qpic.cn/mmsns/oSSMibuEp2Xeh8EfTAYYYZXRoR9dU8VM9DqcdCYrIP0ibCgibSCfn2aVDOGuAolwrcDUS0ZPqMvcTU/150]]>\n" +
         "                </thumbMoment>\n" +
         "                <size totalSize=\\\"146625.0\\\" width=\\\"2280.0\\\" height=\\\"1080.0\\\"></size>\n" +
         "            </media>\n" +
         "        </mediaList>\n" +
         "    </ContentObject>\n" +
         "    <actionInfo>\n" +
         "        <appMsg>\n" +
         "            <mediaTagName></mediaTagName>\n" +
         "            <messageExt></messageExt>\n" +
         "            <messageAction></messageAction>\n" +
         "        </appMsg>\n" +
         "    </actionInfo>\n" +
         "    <appInfo>\n" +
         "        <id></id>\n" +
         "    </appInfo>\n" +
         "    <location poiClassifyId=\\\"\\\" poiName=\\\"\\\" poiAddress=\\\"\\\" poiClassifyType=\\\"0\\\" city=\\\"\\\"></location>\n" +
         "    <publicUserName></publicUserName>\n" +
         "    <streamvideo>\n" +
         "        <streamvideourl></streamvideourl>\n" +
         "        <streamvideothumburl></streamvideothumburl>\n" +
         "        <streamvideoweburl></streamvideoweburl>\n" +
         "    </streamvideo>\n" +
         "</TimelineObject>\n";

         //		第一种参数设置方式（不是很推荐，忒麻烦了0.0）
         //		List<Map<String, String>> paramsList = new ArrayList<Map<String,String>>();
         //		Map<String, String> paramsMap = new HashMap<String, String>();
         //		paramsMap.put("label", "id");//要改变值的标签
         //		paramsMap.put("value", "1");//标签内容替换为
         //		paramsMap.put("empty", "0");//标签值为空的值
         //		Map<String, String> paramsMap1 = new HashMap<String, String>();
         //		paramsMap1.put("label", "username");//要改变值的标签
         //		paramsMap1.put("value", "su");//标签内容替换为
         //		paramsMap1.put("empty", "0");//标签值为空的值
         //		Map<String, String> paramsMap2 = new HashMap<String, String>();
         //		paramsMap2.put("label", "createTime");//要改变值的标签
         //		paramsMap2.put("value", "0");//标签内容替换为
         //		paramsMap2.put("empty", "");//标签值为空的值
         //		paramsList.add(paramsMap);
         //		paramsList.add(paramsMap1);
         //		paramsList.add(paramsMap2);

         //		第二种参数设置方式（推荐用这种配置式的，参数用的可变长度参数列表，有多少写多少~\(≧▽≦)/~）
         //		配置参数表示为-----标签[必填]&替换内容[必填]&空值替换[可选]
         //		id&1&-----------表示要把id标签中的值替换为1,没有空值替换，换后表示为<id>1</id>
         //		username&su&0---表示要把username标签中的值换为su，空值替换为0，换后：1、原标签中有值的替换为<username>su</username>  2、原标签中没有值的替换为<username>0</username>
         //		createTime&0----表示把createTime标签中的值换为0，无空值替换
         List<Map<String, String>> paramsList = xmlConfigStr("id&1&","username&su&0","createTime&0");
         //根据参数配置进行标签内容处理
         String sb = sovleXmlLabelValue(xmlText, paramsList);
         //输出一下处理好的xml
         System.out.println(sb);
         }
         **/
        /**
         * 初始化xml参数字符串
         *
         * @param configParams 初始化字符串 [要替换的标签&标签内替换内容&空值替换内容(该项可选)]，如id&1&0
         * @return 参数设置list
         * @author suguolong
         */
        public static List<Map<String, String>> xmlConfigStr(String... configParams) {
            List<Map<String, String>> paramsList = new ArrayList<Map<String, String>>();
            for (String configParam : configParams) {
                Map<String, String> paramsMap = new HashMap<String, String>();
                String[] params = configParam.split("&");
                int len = params.length;
                paramsMap.put("label", params[0]);//要改变值的标签
                paramsMap.put("value", params[1]);//标签内容替换为
                if (len == 3) {
                    paramsMap.put("empty", params[2]);//标签值为空的值
                }
                paramsList.add(paramsMap);
            }
            return paramsList;
        }

        /**
         * 处理xml中标签中的内容
         *
         * @param xmlText    xml字符串
         * @param paramsList 设置参数list
         * @return 处理好的字符串
         * @author suguolong
         */
        public static String sovleXmlLabelValue(String xmlText, List<Map<String, String>> paramsList) {
            StringBuilder sb = new StringBuilder(xmlText);
            for (int i = 0; i < paramsList.size(); i++) {
                Map<String, String> configMap = paramsList.get(i);
                String label = configMap.get("label");
                String value = configMap.get("value");
                replaceXmlValue(sb, configMap, label, value);
                sb = new StringBuilder(sb.toString().replaceAll("temp_" + label + "_temp", label));
            }
            return sb.toString();
        }

        /**
         * 递归处理标签中的内容
         *
         * @param sb        xml文字
         * @param configMap 初始化设置map
         * @param label     标签
         * @param value     标签中内容
         * @author suguolong
         */
        private static void replaceXmlValue(StringBuilder sb, Map<String, String> configMap, String label, String value) {
            //获取初始化map中的key
            Set<String> keySet = configMap.keySet();
            //如果还有标签，继续处理
            if (sb.indexOf("</" + label) != -1) {
                //如果标签内是空值，并且初始化配置中设置了空值替换
                if (((sb.indexOf("</" + label)) - (sb.indexOf("<" + label)) == (label.length() + 2)) && keySet.contains("empty")) {
                    //取出空值要设置的内容
                    String empty = configMap.get("empty");
                    //将空值替换为设置中的内容
                    sb.replace(sb.indexOf("<" + label), sb.indexOf("</" + label) + 2 + label.length(), "<temp_" + label + "_temp>" + empty + "</temp_" + label + "_temp");
                } else {
                    //其他情况直接替换
                    sb.replace(sb.indexOf("<" + label), sb.indexOf("</" + label) + 2 + label.length(), "<temp_" + label + "_temp>" + value + "</temp_" + label + "_temp");
                }
                //继续处理，直到没有标签
                replaceXmlValue(sb, configMap, label, value);
            }
        }
    }

}
